/*
 * TestTcpClient.cpp
 *
 *   Created on: 2010-1-29     
 *  Description: 
 *    Copyright: 2010 @ ICT Li Heyuan
 */

#include "../include/client/TcpClient.h"
#include "../include/json_cpp/value.h"

using Json::Value;

#include <pthread.h>
#include <unistd.h>

#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
using std::cerr;

void testTcpClient()
{
	Client *pClient = new TcpClient;
	Value param, result;

	pClient->setServerAddr("127.0.0.1", 8080);

	unsigned int a, b;
	a = random() % 100;
	b = random() % 100;

	param.append(Value(a));
	param.append(Value(b));
	if (pClient->call("add", param, result))
	{
		if (result.asUInt() == a + b)
		{
			cout << "rpc call success , " << a << "+" << b << "="
					<< result.asInt() << endl;
		}
		else
		{
			cerr << "rpc add fail." << endl;
		}
	}
	else
	{
		cerr << "rpc call fail." << endl;
	}

	delete pClient;
}

void * t_run(void *)
{

	useconds_t time = random() % 100;

	usleep(time);

	testTcpClient();

	pthread_exit(NULL);
}

void multithread(int n)
{

	pthread_t *tid = new pthread_t[n];

	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	for (int i = 0; i < n; i++)
	{
		if (pthread_create(&tid[i], &attr, t_run, NULL))
		{
			cerr << "thread " << i << " create fail." << endl;
		}
	}
	pthread_attr_destroy(&attr);
	cout << "over" << endl;
}

//测试Client的notification
void testTcpClientNotification()
{
	Client *pClient = new TcpClient;
	Value param, result;

	pClient->setServerAddr("127.0.0.1", 8080);

	unsigned int a, b;
	a = random() % 100;
	b = random() % 100;

	param.append(Value(a));
	param.append(Value(b));
	if (pClient->notification("add", param))
	{
		cout << "rpc notification success" << endl;
	}
	else
	{
		cerr << "rpc notification fail." << endl;
	}

	delete pClient;
}

void testRSAPubMethod2()
{
	TcpClient client("127.0.0.1", 8080);
	Value param, ret;
	if (!client.call("system.getRsaPubKey", param, ret))
	{
		cerr << "fail:" << ret.asString() << endl;
	}
	else
	{
		cout << "success:" << ret.asString() << endl;
	}

}

void * t_run2(void *)
{

	useconds_t time = random() % 100;

	usleep(time);

	testRSAPubMethod2();

	pthread_exit(NULL);
}

void multithread2(int n)
{

	pthread_t *tid = new pthread_t[n];

	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	for (int i = 0; i < n; i++)
	{
		if (pthread_create(&tid[i], &attr, t_run2, NULL))
		{
			cerr << "thread " << i << " create fail." << endl;
		}
	}
	pthread_attr_destroy(&attr);
	cout << "over" << endl;
}

/*
 int main()
 {
 for (int i = 0; i < 2000; i++)
 {
 testRSAPubMethod2();
 }

 multithread2(1000);
 //sleep(5);
 //testTcpClient();
 //	testTcpClientNotification();
 }

 */
